<template>
  <div class="drug-list">
    <el-card>
      <template v-slot:header>
        <span>药品区分性别使用规则</span>
      </template>

      <!-- 筛选区 -->
      <el-form inline :model="filters" class="filter-form">
        <el-form-item label="药品名称">
          <el-input v-model="filters.itemName" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="限定性别">
          <el-select v-model="filters.limitGender" placeholder="请选择" clearable>
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList">查询</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 列表 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%; margin-top: 10px;"
      >
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="serialNumber" label="知识点序号" />
        <el-table-column prop="itemName" label="药品通用名" />
        <el-table-column prop="limitGender" label="限定性别" />
        <el-table-column prop="drugCodeCount" label="药品代码数量" />
        <el-table-column prop="detectLogic" label="检出逻辑" />
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button type="text" @click="$router.push(`/drug/edit/${scope.row.id}`)">编辑</el-button>
            <el-button type="text" @click="handleDelete(scope.row.id)">删除</el-button>
            <!-- 关键：传递 ruleId（即当前规则的 id） -->
            <el-button type="text" @click="$router.push(`/drug/code/${scope.row.id}`)">代码</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 15px; text-align: right;"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import drugApi from '@/api/drugApi.ts'
import { ElMessage, ElMessageBox } from 'element-plus'

// 状态
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const filters = ref({
  itemName: '',
  limitGender: ''
})

// 加载列表
const getList = async () => {
  loading.value = true
  try {
    // 此时 res 直接是 backendRes.data（业务数据）
    const res = await drugApi.getDrugList({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      itemName: filters.value.itemName,
      limitGender: filters.value.limitGender
    })

    // 直接解析业务数据（无需再处理嵌套的 code、msg）
    tableData.value = res.records || []
    total.value = res.total || 0
    pageNum.value = res.current || 1 // 同步当前页
    pageSize.value = res.size || 10 // 同步每页条数

  } catch (err) {
    // 仅处理特殊场景（如清空列表），普通错误已在拦截器提示
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 分页事件
const handleSizeChange = (size) => {
  pageSize.value = size
  getList()
}
const handleCurrentChange = (page) => {
  pageNum.value = page
  getList()
}

// 重置筛选
const resetFilters = () => {
  filters.value = { itemName: '', limitGender: '' }
  pageNum.value = 1
  getList()
}

// 删除
const handleDelete = (id) => {
  ElMessageBox.confirm('确定删除该规则？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await drugApi.deleteDrug(id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.msg)
      }
    } catch (err) {
      ElMessage.error('删除失败：' + err.message)
    }
  })
}

// 初始化加载
onMounted(() => {
  getList()
})
</script>

<style scoped>
.filter-form {
  margin-bottom: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}
</style>
